package com.mima.minaserver.service;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mima.minaserver.entity.FaultEntity;
import com.mima.minaserver.repository.FaultRepository;
import com.mima.minaserver.utils.ParameterUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

@Service
public class MessageSender {
	
	@Autowired
	private ParameterUtils parameterUtils;
	
	@Autowired
	private FaultRepository faultRepository;
	
	private Logger logger = LoggerFactory.getLogger(MessageSender.class);

	public boolean sendIpChangeMessage(String message) {
		
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(parameterUtils.getRabbitmq_host());
	        factory.setUsername(parameterUtils.getRabbitmq_username());
	        factory.setPassword(parameterUtils.getRabbitmq_password());
	        factory.setPort(parameterUtils.getRabbitmq_port());

			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			channel.basicPublish(parameterUtils.getExchange_ip_change(),parameterUtils.getRouting_key_ip_change(), null, message.getBytes());
			logger.info("{SEND MESSAGE:"+message+"}");
			channel.close();
			connection.close();
		} catch (Exception e) {
			logger.error("send message faild!", e);
			return false;
		}
		return true;
	}
	
	
	public boolean sendOnOffAlarmMessage(String message) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(parameterUtils.getRabbitmq_host());
	        factory.setUsername(parameterUtils.getRabbitmq_username());
	        factory.setPassword(parameterUtils.getRabbitmq_password());
	        factory.setPort(parameterUtils.getRabbitmq_port());
			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			channel.basicPublish(parameterUtils.getExchange_on_off_alarm(), parameterUtils.getRouting_key_on_off_alarm(), null, message.getBytes());
			logger.info("Sent MESSAGE'" + message + "'");
			channel.close();
			connection.close();
		} catch (Exception e) {
			logger.error("send message faild!", e);
			return false;
		}
		
		return true;
	}
	
	/**
	 * @param faultStatus 
	 * 			0:解除故障报警  
	 * 			1:用户名故障 
	 * 			2:密码故障 
	 * 			3:key_id故障
	 * @return
	 */
	private String sendFaultMessageIntercept(String uuid,Integer faultStatus) {
		FaultEntity faultEntity = faultRepository.fetchFault(uuid);
		if(0 == faultStatus) {
			if(faultEntity == null) return null;
			if(faultEntity.getFault_status() != 0){
				faultRepository.updateFault(uuid,faultStatus);
				String message = "{\"uuid\":\""+uuid+"\",\"fault_status\":"+faultStatus+",\"time\":\""+ new Date() +"\"}";
				return message;
			}
		}else{  
			Calendar calendar = Calendar.getInstance();
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			int minute = calendar.get(Calendar.MINUTE);
			String period = parameterUtils.getPeriod();
			String[] times = period.split("-");
			String startTime =  times[0];
			String endTime =  times[1];
			
			String[] startTimeTemp = startTime.split(":");
			int periodMinHour = Integer.parseInt(startTimeTemp[0]);
			int periodMinMinute = Integer.parseInt(startTimeTemp[1]);
			
			String[] endTimeTemp = endTime.split(":");
			int periodMaxHour = Integer.parseInt(endTimeTemp[0]);
			int periodMaxMinute = Integer.parseInt(endTimeTemp[1]);
			
			//判断是否在压制时间范围内
			if((hour >= periodMinHour && minute >=periodMinMinute)&&(hour <= periodMaxHour && minute <=periodMaxMinute))  return null;
			if(faultEntity==null) {
				faultEntity = new FaultEntity(uuid, faultStatus, new Date());
				faultRepository.save(faultEntity);
				String message = "{\"uuid\":\""+uuid+"\",\"fault_status\":"+faultStatus+",\"time\":\""+ new Date() +"\"}";
				return message;
			}
			if(faultEntity.getFault_status() == faultStatus) return null;
			faultRepository.updateFault(uuid, faultStatus);
			String message = "{\"uuid\":\""+uuid+"\",\"fault_status\":"+faultStatus+",\"time\":\""+ new Date() +"\"}";
			return message;
		}
		return null;
			
	}
	public boolean sendFaultMessage(String uuid,Integer faultStatus) {
		try {
			logger.info("Receive---{uuid="+uuid+",faultStatus="+faultStatus+",time="+new Date()+"}");
			String message = sendFaultMessageIntercept(uuid,faultStatus);
			if(org.springframework.util.StringUtils.isEmpty(message)) return false;
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(parameterUtils.getRabbitmq_host());
	        factory.setUsername(parameterUtils.getRabbitmq_username());
	        factory.setPassword(parameterUtils.getRabbitmq_password());
	        factory.setPort(parameterUtils.getRabbitmq_port());
			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			channel.basicPublish(parameterUtils.getExchange_fault_alarm(), parameterUtils.getRouting_key_fault(), null, message.getBytes());
			logger.info("Sent MESSAGE'" + message + "'");
			channel.close();
			connection.close();
		} catch (Exception e) {
			logger.error("send message faild!", e);
			return false;
		}
		
		return true;
	}
	
}